package com.cibfintech.rpa.jdwzcx.controller;

import com.cibfintech.rpa.jdwzcx.util.MessageDigestUtil;
import com.google.common.base.Optional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@Slf4j
@RestController
@RequestMapping("/wx/mp")
public class WxMpController {

    /**
     * 微信服务认证，用于微信公众号的接入
     * 开发者通过检验signature对请求进行校验，加密/校验流程如下：<br/>
     * 1）将token、timestamp、nonce三个参数进行字典序排序<br/>
     * 2）将三个参数字符串拼接成一个字符串进行sha1加密<br/>
     * 3）开发者获得加密后的字符串可与signature对比，标识该请求来源于微信
     *
     * @param request
     * @param response
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return 验证成功返回echostr ，否则返回空字符串
     */
    @RequestMapping(value = "/service", method = RequestMethod.GET)
    @ResponseBody
    public String validate(HttpServletRequest request, HttpServletResponse response,
                           @RequestParam(value = "signature") String signature,
                           @RequestParam(value = "timestamp") String timestamp,
                           @RequestParam(value = "nonce") String nonce,
                           @RequestParam(value = "echostr") String echostr) {
        log.info("request from WeiXin Server signature={} , timestamp={} , nonce={} , echostr={}",
                signature, timestamp, nonce, echostr);

//        Optional<Project> projectOptional = projectCache.getProjectById(projectId);
//
//        if (!projectOptional.isPresent()) {
//            log.info("project id {} is is not exist", projectId);
//            return "";
//        }
//
//        Optional<WxApplicationInfo> optional = wxApplicationInfoCache.getWxApplicationInfo(projectOptional.get().getApplicationId());
//
//        if (!optional.isPresent()) {
//            log.info("application id {} is not exist");
//            return "";
//        }
//
//        String[] arrs = new String[]{optional.get().getToken(), timestamp, nonce};
//        Arrays.sort(arrs);
//        StringBuilder builder = new StringBuilder();
//        for (String tmp : arrs) {
//            builder.append(tmp);
//        }
//
//        try {
//            String factSignature = MessageDigestUtil.sha1(builder.toString());
//            boolean isSuccess = signature.equalsIgnoreCase(factSignature);
//            log.info("signature={} , factSignature={} , isSuccess={}", signature, factSignature, isSuccess);
//            if (isSuccess) {
//                return echostr;
//            }
//        } catch (Exception e) {
//            log.error("validate wei xin service exception", e);
//        }

        return "";
    }

}
